﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Moq;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace AutoPartsSearch.Web.Tests.Helpers
{
    public static class JsonUtils
    {
        public static T GetJsonObjectRepresentation<T>(JsonResult jsonResult)
        {
            var controllerContext = new Mock<ControllerContext>();
            var httpContext = new Mock<HttpContextBase>();
            var httpResponse = new Mock<HttpResponseBase>();
            var sb = new StringBuilder();

            httpResponse.Setup(x => x.Write(It.IsAny<string>()))
                .Callback<string>(y => sb.Append(y));
            httpContext.Setup(x => x.Response).Returns(httpResponse.Object);
            controllerContext.Setup(x => x.HttpContext).Returns(httpContext.Object);

            jsonResult.ExecuteResult(controllerContext.Object);

            var serializer = new JavaScriptSerializer();
            return serializer.Deserialize<T>(sb.ToString());
        }
    }
}
